﻿using WebApp.BLL;
using WebApp.BLL.Manage;
using WebApp.Common.Caching;
using WebApp.Models;
using WebApp.ViewModels.Manage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApp.Web.Core
{
    public class UserCache
    {
        /// <summary>
        /// 菜单缓存KEY
        /// </summary>
        private const string MENU_ALL_KEY = "WebApp.Sysmenu.all";
        /// <summary>
        /// 用户菜单缓存KEY
        /// </summary>
        /// <remarks>
        /// {0} : userid
        /// </remarks>
        private const string USERMENU_ALL_KEY = "WebApp.Sysmenu.all-{0}";

        /// <summary>
        /// 用户权限缓存KEY
        /// </summary>
        /// <remarks>
        /// {0} : userid
        /// </remarks>
        private const string USERAUTH_ALL_KEY = "WebApp.Sysmenu.auth.all-{0}";

        /// <summary>
        /// 菜单KEY(清除缓存用)
        /// </summary>
        private const string USERMENU_PATTERN_KEY = "WebApp.Sysmenu.";

        /// <summary>
        /// 初始化用户菜单缓存
        /// </summary>
        /// <param name="user"></param>
        public static void InitUsreCache(SessionUserModel user)
        {
            var menuservice = new S_menuService();

            IList<S_menu> allMenuList = null;
            List<UserMenuModel> userMenuList = new List<UserMenuModel>();
            IList<Auth.Auth> allUserAuthList = new List<Auth.Auth>();
            string[] menuKinds = new string[] { enmMenuKind.模块.ToString("d"), enmMenuKind.菜单.ToString("d") };

            //超级管理员
            if (IsSuperAdmin(user))
            {
                allMenuList = menuservice.GetAllMenus();
            }
            else
            {
                allMenuList = new S_userService().GetUsermenusByUserid(user.Id);
            }

            //权限
            foreach (var item in allMenuList)
            {
                allUserAuthList.Add(new Auth.Auth
                {
                    Authcode = item.Menuid,
                    Authname = menuservice.GetName(item)
                });
            }

            userMenuList.AddRange(getChildMenus(allMenuList, ""));

            ////两级菜单结构
            //foreach (var item in allMenuList.Where(p => string.IsNullOrEmpty(p.Pmenuid) && menuKinds.Contains(p.Menukind)))
            //{
            //    if (item.Menukind == enmMenuKind.功能.ToString("d"))
            //        continue;

            //    var menu = new UserMenuModel
            //    {
            //        Menuid = item.Menuid,
            //        Menuname = menuservice.GetName(item),
            //        Menuurl = item.Menuurl,
            //        Menuicon = item.Menuiconmiddle,
            //        Menukind = item.Menukind,
            //        Status = item.Status,
            //        ChildMenus = new List<UserMenuModel>()
            //    };

            //    foreach (var submenu in allMenuList.Where(p => p.Pmenuid == item.Menuid && menuKinds.Contains(p.Menukind)))
            //    {
            //        if (item.Menukind == enmMenuKind.功能.ToString("d"))
            //            continue;

            //        menu.ChildMenus.Add(new UserMenuModel
            //        {
            //            Menuid = submenu.Menuid,
            //            Menuname = menuservice.GetName(submenu),
            //            Menuurl = submenu.Menuurl,
            //            Menuicon = submenu.Menuiconmiddle,
            //            Menukind = submenu.Menukind,
            //            Status = submenu.Status,
            //            ChildMenus = new List<UserMenuModel>()
            //        });
            //    }

            //    userMenuList.Add(menu);
            //}

            //#region 如果用户没有任何权限，至少给一个课题权限
            
            //if (allUserAuthList.Count == 0)
            //{
            //    allUserAuthList.Add(new Auth.Auth
            //    {
            //        Authcode = "Study",
            //        Authname = "科研管理"
            //    });
            //}
            //if (userMenuList.Count == 0)
            //{
            //    var studymenu = new S_menuService().GetByMenuid("Study");
            //    userMenuList.Add(new UserMenuModel
            //    {
            //        Menuid = studymenu.Menuid,
            //        Menuname = studymenu.Menuname_zho,
            //        Menuurl = studymenu.Menuurl,
            //        Menuicon = studymenu.Menuiconmiddle,
            //        Menukind = studymenu.Menukind,
            //        Status = studymenu.Status,
            //        ChildMenus = new List<UserMenuModel>()
            //    });
            //}

            //#endregion

            //权限缓存
            string authkey = string.Format(USERAUTH_ALL_KEY, user.Id);
            new MemoryCacheManager().Remove(authkey);
            new MemoryCacheManager().Set(authkey, allUserAuthList, 24 * 60);

            //菜单缓存
            string key = string.Format(USERMENU_ALL_KEY, user.Id);
            new MemoryCacheManager().Remove(key);
            new MemoryCacheManager().Set(key, userMenuList, 24 * 60);
        }

        private static List<UserMenuModel> getChildMenus(IList<S_menu> allMenuList, string parentMenuId)
        {
            string[] menuKinds = new string[] { enmMenuKind.模块.ToString("d"), enmMenuKind.菜单.ToString("d") };

            var list = new List<UserMenuModel>();

            foreach (var item in allMenuList.Where(p => p.Pmenuid == parentMenuId && menuKinds.Contains(p.Menukind)))
            {
                if (item.Menukind == enmMenuKind.功能.ToString("d"))
                    continue;

                list.Add(new UserMenuModel
                {
                    Menuid = item.Menuid,
                    Menuname = new S_menuService().GetName(item),
                    Menuurl = item.Menuurl,
                    Menuicon = item.Menuiconmiddle,
                    Menukind = item.Menukind,
                    Status = item.Status,
                    ChildMenus = getChildMenus(allMenuList, item.Menuid)
                });
            }

            return list;
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="user"></param>
        public static void ClearUserCache(int userid)
        {
            //权限缓存
            string authkey = string.Format(USERAUTH_ALL_KEY, userid);
            new MemoryCacheManager().Remove(authkey);
            //菜单缓存
            string key = string.Format(USERMENU_ALL_KEY, userid);
            new MemoryCacheManager().Remove(key);
        }

        public static IList<Auth.Auth> GetUserAuths(SessionUserModel user)
        {
            string authkey = string.Format(USERAUTH_ALL_KEY, user.Id);

            if (!new MemoryCacheManager().IsSet(authkey))
            {
                InitUsreCache(user);
            }

            var list = new MemoryCacheManager().Get<List<Auth.Auth>>(authkey);

            if (list == null || list.Count == 0)
            {
                InitUsreCache(user);
            }

            return list;
        }

        public static IList<UserMenuModel> GetUsermenus(SessionUserModel user)
        {
            string key = string.Format(USERMENU_ALL_KEY, user.Id);

            if (!new MemoryCacheManager().IsSet(key))
            {
                InitUsreCache(user);
            }

            var list = new MemoryCacheManager().Get<IList<UserMenuModel>>(key);

            if (list == null || list.Count == 0)
            {
                InitUsreCache(user);
            }

            return list;
        }

        /// <summary>
        /// 获取子菜单
        /// </summary>
        /// <returns></returns>
        public static IList<UserMenuModel> GetAuthMenusByPid(string menuid)
        {
            var list = GetUsermenus(SessionManage.User);

            var menu = list.FirstOrDefault(p => p.Menuid == menuid);
            if (menu == null)
            {
                return new List<UserMenuModel>();
            }
            else
            {
                return menu.ChildMenus;
            }
        }

        /// <summary>
        /// 判断用户是否为超级管理员
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static bool IsSuperAdmin(SessionUserModel user)
        {
            return "manage".Equals(user.Username, StringComparison.OrdinalIgnoreCase)
                || "dev".Equals(user.Username, StringComparison.OrdinalIgnoreCase);
            //return "manage".Equals(user.Username);
            //return SessionManage.UserRoles.Contains("A0000");
        }

    }
}
